<?php
use Phalcon\Di;
use MongoDB\BSON\ObjectID;
use Modules\Book\Models\NodeBook;

$di->getShared('eventsManager')->attach('entity', new \Modules\Book\Library\EntityListener());

function nodeBookActionLink($node)
{
    $di = Di::getDefault();
    $url = $di->getShared('url');
    $bookNode = $di->getShared('entityManager')->get('node', [
        'conditions' => [
            '_id' => new ObjectID($node->book_id)
        ]
    ]);
    $nodeBook = NodeBook::findFirst([
        'conditions' => [
            'bid' => $node->book_id
        ]
    ]);
    $output = [
        'up' => [
            'href' => '#null',
            'label' => '上一篇',
            'title' => '没有了～'
        ],
        'book' => [
            'href' => '#null',
            'label' => '书本目录',
            'title' => '没有了～'
        ],
        'next' => [
            'href' => '#null',
            'label' => '下一篇',
            'title' => '没有了～'
        ]
    ];

    if ($nodeBook && $bookNode) {
        $actionOutput = multInfoArrayActionInfo(objectToArray($nodeBook->toc), strval($node->getId()));
        $output['book']['href'] = $url->get(['for' => 'node', 'contentModel' => $bookNode->contentModel, 'id' => $bookNode->getId()]);
        $output['book']['title'] = $bookNode->title;

        if ($actionOutput['up']) {
            $upData = $actionOutput['up'];

            $output['up']['href'] = $url->get(['for' => 'node', 'contentModel' => $upData['contentModel'], 'id' => $upData['id']]);
            $output['up']['title'] = $upData['title'];
        }
        if ($actionOutput['next']) {
            $nextData = $actionOutput['next'];

            $output['next']['href'] = $url->get(['for' => 'node', 'contentModel' => $nextData['contentModel'], 'id' => $nextData['id']]);
            $output['next']['title'] = $nextData['title'];

        }
    }

    return $output;
}

//函数库
function bookRender($id, $nodeToc)
{
    $di = \Phalcon\Di::getDefault();
    $data = \Modules\Book\Models\NodeBook::findFirst([
        'conditions' => [
            'bid' => $id,
        ]
    ]);
    $bookNode = $di->getShared('entityManager')->get('node', [
        'conditions' => [
            '_id' => new \MongoDB\BSON\ObjectID($id)
        ]
    ]);
    if (!$data || !$bookNode) {
        return false;
    }
    $output = array(
        '#templates' => array(
            'bookToc',
            'bookToc-' . $id
        ),
        'currentId' => $id,
        'bookNode' => $bookNode,
        'nodeToc' => $nodeToc,
        'data' => $data
    );
    return $output;
}